package base.web.controller;

import base.service.IAliPayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import common.*;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
 * 支付宝支付控制器
 * @author LiuZhi
 */
@Controller@Scope("prototype")
public class AliPayController
{
    @Autowired
    IAliPayService iAliPayService;

    @RequireLogin
    @RequestMapping("/alipay.do")
    @ResponseBody
    public ServerResponse pay(String money, HttpServletRequest request)
    {
        if(UserContext.getCurrentUser()==null)
        {
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        return iAliPayService.pay(money,path);
    }

    @RequestMapping("/alipay_callback.do")
    @ResponseBody
    public Object payCallback(HttpServletRequest request)
    {
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParameters = request.getParameterMap();
        Iterator iterator = requestParameters.keySet().iterator();
        while (iterator.hasNext())
        {
            String name     = (String) iterator.next();
            String[] values = (String[]) requestParameters.get(name);
            String valueStr = "";
            for(int i = 0;i < values.length;i++)
            {
                valueStr = (i == values.length -1 ) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name,valueStr);
        }
        //验证回调的正确性且避免重复通知
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
            if(!alipayRSACheckedV2)
            {
                return ServerResponse.createByErrorMsg("非法请求,验证不通过");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        try {
            ServerResponse sr = iAliPayService.aliCallBack(params);
            if(sr.isSuccess())
            {
                return Const.aliPayCallBack.RESPONSE_SUCCESS;
            }
            return Const.aliPayCallBack.RESPONSE_FAILED;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Const.aliPayCallBack.RESPONSE_FAILED;
    }

    @RequireLogin
    @RequestMapping("/queryPay.do")
    @ResponseBody
    public ServerResponse queryPay(String tradeCode)
    {
        return iAliPayService.queryPay(tradeCode);
    }

}
